package com.gxc.healthfood.controller;

import com.gxc.healthfood.common.ResponseResult;
import com.gxc.healthfood.entity.DietPlans;
import com.gxc.healthfood.service.DietPlansService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 饮食计划控制器，处理饮食计划相关的HTTP请求
 */@RestController
@RequestMapping("/diet-plans")
public class DietPlansController {

    private static final Logger log = LoggerFactory.getLogger(DietPlansController.class);

    @Autowired
    private DietPlansService dietPlansService;

    /**
     * 创建饮食计划
     * @param dietPlan 饮食计划数据
     * @return 创建结果
     */
    @PostMapping
    public ResponseResult<Map<String, Object>> createDietPlan(@RequestBody DietPlans dietPlan) {
        try {
            // 参数验证
            if (dietPlan == null) {
                return ResponseResult.error("饮食计划数据不能为空");
            }

            if (dietPlan.getUserId() == null) {
                return ResponseResult.error("用户ID不能为空");
            }

            if (dietPlan.getName() == null || dietPlan.getName().trim().isEmpty()) {
                return ResponseResult.error("饮食计划名称不能为空");
            }

            if (dietPlan.getName().length() > 100) {
                return ResponseResult.error("饮食计划名称不能超过100个字符");
            }

            if (dietPlan.getTotalCalories() == null || dietPlan.getTotalCalories().compareTo(BigDecimal.ZERO) < 0) {
                return ResponseResult.error("总热量不能为负数");
            }

            if (dietPlan.getTotalProtein() == null || dietPlan.getTotalProtein().compareTo(BigDecimal.ZERO) < 0) {
                return ResponseResult.error("总蛋白质不能为负数");
            }

            if (dietPlan.getTotalFat() == null || dietPlan.getTotalFat().compareTo(BigDecimal.ZERO) < 0) {
                return ResponseResult.error("总脂肪不能为负数");
            }

            if (dietPlan.getTotalCarbohydrate() == null || dietPlan.getTotalCarbohydrate().compareTo(BigDecimal.ZERO) < 0) {
                return ResponseResult.error("总碳水化合物不能为负数");
            }

            if (dietPlan.getGoal() == null) {
                return ResponseResult.error("饮食目标不能为空");
            }

            // 设置创建时间
            dietPlan.setCreatedAt(new Date());

            // 保存饮食计划
            boolean success = dietPlansService.save(dietPlan);

            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("id", dietPlan.getId());
                result.put("message", "饮食计划创建成功");
                return ResponseResult.success("创建成功", result);
            } else {
                return ResponseResult.error("创建失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("创建饮食计划异常: {}", e.getMessage(), e);
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 根据用户ID获取饮食计划列表
     * @param userId 用户ID
     * @param page 页码，默认1
     * @param pageSize 每页数量，默认10
     * @param active 是否仅获取激活的计划，可选参数
     * @return 饮食计划列表
     */
    @GetMapping("/user/{userId}")
    public ResponseResult<Map<String, Object>> getDietPlansByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer active) {
        try {
            if (userId == null) {
                return ResponseResult.error("用户ID不能为空");
            }

            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("userId", userId);
            if (active != null) {
                queryParams.put("active", active);
            }

            // 计算偏移量
            int offset = (page - 1) * pageSize;

            // 查询饮食计划列表
            List<DietPlans> dietPlansList = dietPlansService.lambdaQuery()
                    .eq(DietPlans::getUserId, userId)
                    .orderByDesc(DietPlans::getCreatedAt)
                    .last("LIMIT " + offset + "," + pageSize)
                    .list();

            // 查询总数
            long total = dietPlansService.lambdaQuery()
                    .eq(DietPlans::getUserId, userId)
                    .count();

            Map<String, Object> result = new HashMap<>();
            result.put("list", dietPlansList);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);

            return ResponseResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取饮食计划列表异常: {}", e.getMessage(), e);
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }
    @GetMapping("/userActivity/{userId}")
    public ResponseResult<Map<String, Object>> getDietPlansByUserIdAndActivity(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer active) {
        try {
            if (userId == null) {
                return ResponseResult.error("用户ID不能为空");
            }

            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("userId", userId);
            if (active != null) {
                queryParams.put("active", active);
            }

            // 计算偏移量
            int offset = (page - 1) * pageSize;

            // 查询饮食计划列表
            List<DietPlans> dietPlansList = dietPlansService.lambdaQuery()
                    .eq(DietPlans::getUserId, userId)
                    .orderByDesc(DietPlans::getCreatedAt)
                    .eq(DietPlans::getActive,active)
                    .last("LIMIT " + offset + "," + pageSize)
                    .list();

            // 查询总数
            long total = dietPlansService.lambdaQuery()
                    .eq(DietPlans::getUserId, userId)
                    .eq(DietPlans::getActive,active)
                    .count();

            Map<String, Object> result = new HashMap<>();
            result.put("list", dietPlansList);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);

            return ResponseResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取饮食计划列表异常: {}", e.getMessage(), e);
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 获取单个饮食计划详情
     * @param id 饮食计划ID
     * @return 饮食计划详情
     */
    @GetMapping("/{id}")
    public ResponseResult<DietPlans> getDietPlanDetail(@PathVariable Long id) {
        try {
            if (id == null) {
                return ResponseResult.error("饮食计划ID不能为空");
            }

            // 查询饮食计划详情
            DietPlans dietPlan = dietPlansService.getById(id);

            if (dietPlan != null) {
                return ResponseResult.success("获取成功", dietPlan);
            } else {
                return ResponseResult.error("饮食计划不存在");
            }
        } catch (Exception e) {
            log.error("获取饮食计划详情异常: {}", e.getMessage(), e);
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }


//     * 更新饮食计划
//
//     * @param id 饮食计划ID
//
//     * @param dietPlan 更新的饮食计划数据
//
//     * @return 更新结果
//
//     */

    @PutMapping("/{id}")

    public ResponseResult<Map<String, Object>> updateDietPlan(@PathVariable Long id, @RequestBody DietPlans dietPlan) {

        try {

            if (id == null) {

                return ResponseResult.error("饮食计划ID不能为空");

            }

            if (dietPlan == null) {

                return ResponseResult.error("饮食计划数据不能为空");

            }

// 检查饮食计划是否存在

            DietPlans existingPlan = dietPlansService.getById(id);

            if (existingPlan == null) {

                return ResponseResult.error("饮食计划不存在");

            }

// 更新饮食计划信息

            if (dietPlan.getName() != null) {

                if (dietPlan.getName().trim().isEmpty()) {

                    return ResponseResult.error("饮食计划名称不能为空");

                }

                if (dietPlan.getName().length() > 100) {

                    return ResponseResult.error("饮食计划名称不能超过100个字符");

                }

                existingPlan.setName(dietPlan.getName());

            }

            if (dietPlan.getDescription() != null) {

                existingPlan.setDescription(dietPlan.getDescription());

            }

            if (dietPlan.getTotalCalories() != null) {

                if (dietPlan.getTotalCalories().compareTo(BigDecimal.ZERO) < 0) {

                    return ResponseResult.error("总热量不能为负数");

                }

                existingPlan.setTotalCalories(dietPlan.getTotalCalories());

            }

            if (dietPlan.getTotalProtein() != null) {

                if (dietPlan.getTotalProtein().compareTo(BigDecimal.ZERO) < 0) {

                    return ResponseResult.error("总蛋白质不能为负数");

                }

                existingPlan.setTotalProtein(dietPlan.getTotalProtein());

            }

            if (dietPlan.getTotalFat() != null) {

                if (dietPlan.getTotalFat().compareTo(BigDecimal.ZERO) < 0) {

                    return ResponseResult.error("总脂肪不能为负数");

                }

                existingPlan.setTotalFat(dietPlan.getTotalFat());

            }

            if (dietPlan.getTotalCarbohydrate() != null) {

                if (dietPlan.getTotalCarbohydrate().compareTo(BigDecimal.ZERO) < 0) {

                    return ResponseResult.error("总碳水化合物不能为负数");

                }

                existingPlan.setTotalCarbohydrate(dietPlan.getTotalCarbohydrate());

            }

            if (dietPlan.getGoal() != null) {

                existingPlan.setGoal(dietPlan.getGoal());

            }

            if (dietPlan.getStartDate() != null) {

                existingPlan.setStartDate(dietPlan.getStartDate());

            }

            if (dietPlan.getEndDate() != null) {

                existingPlan.setEndDate(dietPlan.getEndDate());

            }

// 保存更新

            boolean success = dietPlansService.updateById(existingPlan);

            if (success) {

                Map<String, Object> result = new HashMap<>();

                result.put("message", "饮食计划更新成功");

                return ResponseResult.success("更新成功", result);

            } else {

                return ResponseResult.error("更新失败，请稍后重试");

            }

        } catch (Exception e) {

            log.error("更新饮食计划异常: {}", e.getMessage(), e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }
    @RequestMapping("/diet-plans")/**

     * 激活/停用饮食计划

     * @param id 饮食计划ID

     * @param active 是否激活（1-激活，0-停用）

     * @return 操作结果

     */

    @PutMapping("/{id}/active")

    public ResponseResult<Map<String, Object>> setDietPlanActive(@PathVariable Long id, @RequestParam Integer active) {

        try {

            if (id == null) {

                return ResponseResult.error("饮食计划ID不能为空");

            }

            if (active == null || (active != 0 && active != 1)) {

                return ResponseResult.error("激活状态参数无效，只能是0或1");

            }

// 检查饮食计划是否存在

            DietPlans dietPlan = dietPlansService.getById(id);

            if (dietPlan == null) {

                return ResponseResult.error("饮食计划不存在");

            }

// 如果设置为激活状态，先将该用户的其他激活计划设置为非激活

            if (active == 1) {

                dietPlansService.lambdaUpdate()

                        .eq(DietPlans::getUserId, dietPlan.getUserId())

                        .eq(DietPlans::getActive, 1)

                        .set(DietPlans::getActive, 0)

                        .update();

            }

// 更新当前计划的激活状态

            dietPlan.setActive(active);

            boolean success = dietPlansService.updateById(dietPlan);

            if (success) {

                Map<String, Object> result = new HashMap<>();

                result.put("message", active == 1 ? "饮食计划已激活" : "饮食计划已停用");

                return ResponseResult.success(active == 1 ? "激活成功" : "停用成功", result);

            } else {

                return ResponseResult.error("操作失败，请稍后重试");

            }

        } catch (Exception e) {

            log.error("设置饮食计划激活状态异常: {}", e.getMessage(), e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }
 }